package classes {
	import UIFree.ObjectEvent;
	
	import components.c_component;
	
	import flash.events.Event;
	import flash.events.KeyboardEvent;

	public class c_historyList {
		private var _app	: collages;
		private var _list	: Array;
		private var _index	: int;
		
		public function c_historyList(a_app: collages) {
			_app 	= a_app;
			_list 	= new Array();
			_index 	= -1;
			listenEvents();
		}
		
		protected function disposeTopItems(startIndex: int): void {
			for (var i: int=startIndex; i<_list.length; i++) {
				_list[i].removeComponents();
			}
			_list.splice(startIndex, _list.length - startIndex);
			_index = _list.length - 1;
		}
		
		protected function listenEvents(): void {
			_app.workspace.addEventListener(c_events.UNDO, doUndo);
			_app.workspace.addEventListener(c_events.REDO, doRedo);
			_app.stage.addEventListener(KeyboardEvent.KEY_DOWN, doKeyDown);
		}
		
		protected function doKeyDown(e: KeyboardEvent): void {
			if (e.ctrlKey) {
				switch (e.keyCode) {
					case 90:  doUndo(); break;
					case 89:  doRedo(); break;
				}
			}
		}
		
		protected function doSaveStateHistory(e: Event): void {
			if (_index < _list.length - 1) disposeTopItems(_index);
			var result: c_historyItem = new c_historyItem();
			_app.workspace.dispatchEvent(new ObjectEvent(c_events.GETHISTORY, result));
			_list.push(result);
			_index = _list.length - 1;
		}
		
		protected function restoreIndexOf(index: int): void {
			_list[index].states.forEach(function(item : Object, i: int, arr: Array): void {
				item.component.restoreFromHistoryInfo(item.state);
			});
		}
		
		protected function doUndo(e: Event=null): void {
			if (_index > 0) {
				_index--;
				restoreIndexOf(_index);
			}
		}
		
		protected function doRedo(e: Event=null): void {
			if (_index < _list.length) {
				restoreIndexOf(_index);
				_index++;
			}
		}
	}
}